<template>
  <div class="base-info">
    <div class="info-title-box">
      <span class="info-title">产业简介</span>
    </div>
    <div class="introduct-main">
      <div class="logo-box">
        <img class="logo" :src="logoUrl" />
      </div>
      <div class="introduct-text">
        <span class="int-title">
          {{ industryName }}
        </span>
        <div class="text-style int-desc-wrapper" ref="descWrapperRef">
          <!-- <van-text-ellipsis
            :rows="3"
            :content="introText"
            expand-text="展开"
            collapse-text="收起"
          /> -->
          <span class="int-desc">
            <template v-if="!isExpanded">
              <span v-html="displayText"></span>
              <span
                v-if="showExpandBtn"
                class="expand-btn"
                @click="toggleExpand"
              >
                展开
              </span>
            </template>
            <template v-else>
              <span v-html="introText"></span>
              <span class="expand-btn" @click="toggleExpand">收起</span>
            </template>
          </span>
        </div>
      </div>
    </div>
    <div class="info-title-box">
      <span class="info-title">产业趋势</span>
    </div>
    <div class="introduct-main industry-trend">
      <span class="text-style" v-html="trendText"></span>
    </div>
  </div>
</template>
<script setup>
import { ref, onMounted, defineProps, watch, nextTick } from 'vue';
import { useRoute } from 'vue-router';

import { getIndustryByName, getIndustryDetailById } from '@/api/industryMap';

import defaultLogoUrl from '@/assets/images/industryMap/default.png';

const route = useRoute();
const props = defineProps({
  industryId: {
    type: String,
    default: '',
  },
  industryName: {
    type: String,
    default: '',
  },
});
const trendText = ref('');
const logoUrl = ref('');
const handleLogoUrl = (url) => {
  // 有些产业logo是静态资源，需要替换为默认图
  if (/^http/.test(url)) {
    return url;
  } else {
    return defaultLogoUrl;
  }
};
const getIndustryDetail = async () => {
  if (!props.industryName) return;
  const params = {
    industryName: props.industryName,
  };
  const res = await getIndustryByName(params);
  if (res.code == 200 && res.data && res.data.length) {
    logoUrl.value = handleLogoUrl(res.data[0].logoUrl);
  }
};
// 获取产业简介 layerId===>20
const getIntroduct = async () => {
  const params = {
    industryId: props.industryId,
    layerId: 20,
  };
  const res = await getIndustryDetailById(params);
  const data = res.data || {};
  introText.value = (data.richText || '').replace(/\n|\n\n/gi, '<br/>');
  calcTruncate();
};

// 获取产业趋势 layerId===>22
const getIndustryTrend = async () => {
  const params = {
    industryId: props.industryId,
    layerId: 22,
  };
  const res = await getIndustryDetailById(params);
  trendText.value = res.data?.richText;
  trendText.value = trendText.value.replace(/\n|\n\n/gi, '<br/>');
};

const descWrapperRef = ref();
// 展开按钮相关
const isExpanded = ref(false);
const displayText = ref('');
const showExpandBtn = ref(false);
const introText = ref('');
const toggleExpand = () => {
  isExpanded.value = !isExpanded.value;
};
const calcTruncate = () => {
  nextTick(() => {
    if (!descWrapperRef.value) return;
    const width = descWrapperRef.value.offsetWidth;
    if (!width) return; // 宽度为0时不计算
    const computedStyle = window.getComputedStyle(descWrapperRef.value);
    const lineHeight = parseFloat(computedStyle.lineHeight) || 34;
    // 获取当前rem基准值
    const remSize = 200; // 直接使用固定值简化计算
    const lineHeightPx = 38; //原始行高px单位
    const fontSizePx = 24; // 字体大小px单位
    const lineHeightRem = lineHeightPx / remSize; // 转换为rem单位
    const fontSizeRem = fontSizePx / remSize; // 转换为rem单位
    const maxHeight = lineHeight * 3 + 2; // 计算最大允许高度（2行高度）+2 临界点计算会偏小
    // 创建隐藏的span用于测量
    const temp = document.createElement('span');
    temp.style.visibility = 'hidden';
    temp.style.position = 'fixed';
    temp.style.zIndex = '-9999';
    temp.style.fontSize = fontSizeRem + 'rem';
    temp.style.lineHeight = lineHeightRem + 'rem';
    temp.style.fontWeight = '400';
    temp.style.letterSpacing = 'normal';
    temp.style.whiteSpace = 'normal';
    temp.style.width = width + 'px';
    temp.style.display = 'block';
    document.body.appendChild(temp);
    let text = introText.value;
    // 先测量按钮宽度
    const btnText = `<span class="expand-btn" style="display:inline-block;width:120px;font-size:${fontSizeRem}rem;">展开</span>`;
    temp.innerHTML = btnText;
    const btnWidth = temp.offsetWidth;
    // 二分法查找截断点
    let left = 0,
      right = text.length,
      res = text.length;
    while (left <= right) {
      let mid = Math.floor((left + right) / 2);
      temp.innerHTML = text.slice(0, mid) + `...${btnText}`;
      if (temp.offsetHeight > maxHeight) {
        right = mid - 1;
      } else {
        res = mid;
        left = mid + 1;
      }
    }
    // 判断是否需要展开按钮
    temp.innerHTML = text;
    showExpandBtn.value = temp.offsetHeight > maxHeight;
    if (showExpandBtn.value) {
      displayText.value = text.slice(0, res) + '...';
    } else {
      displayText.value = text;
    }
    document.body.removeChild(temp);
  });
};
// 展开按钮相关 end
watch(
  () => props.industryName, // 监听 props.industryName 的变化
  (nawVal) => {
    getIndustryDetail();
    getIndustryTrend();
  },
  { deep: true }
);
watch(
  () => props.industryId, // 监听 props.industryId 的变化
  (nawVal) => {
    getIntroduct();
  },
  { deep: true }
);
onMounted(() => {
  getIntroduct();
  getIndustryDetail();
  getIndustryTrend();
});
</script>

<style lang="scss" scoped>
.base-info {
  height: 100%;
  padding: 48px;
  margin-bottom: 28px;
  background: #ffffff;
  border-radius: 32px;
  backdrop-filter: blur(24px);
  overflow-y: auto;
  .info-title-box {
    margin-bottom: 28px;
    font-weight: bold;
    font-size: 26px;
    color: #222222;
    line-height: 28px;
    .info-title {
      position: relative;
      padding: 0 14px;
      &::after {
        content: '';
        position: absolute;
        bottom: 0;
        left: 0;
        width: 100%;
        height: 11px;
        background: rgba(72, 128, 255, 0.18);
        border-radius: 3px;
        z-index: -1;
      }
    }
  }
}
.introduct-main {
  margin-top: 28px;
  margin-bottom: 60px;
  display: flex;
  .logo-box {
    width: 366px;
    height: 180px;
    background: #ffffff;
    border-radius: 12px;
    img {
      width: 100%;
      height: 100%;
      border-radius: 12px;
    }
  }
  .introduct-text {
    flex: 1;
    margin-left: 20px;
    display: flex;
    flex-direction: column;
    .int-title {
      margin-top: 6px;
      font-weight: bold;
      font-size: 25px;
      color: #222222;
      line-height: 36px;
    }
    .int-desc-wrapper {
      margin-top: 12px;
      line-height: 40px;
      .expand-btn {
        color: #4880ff;
        cursor: pointer;
        font-size: 24px;
        margin-left: 2px;
        white-space: nowrap;
      }
    }
  }
  .text-style {
    font-weight: 400;
    font-size: 24px;
    color: #555555;
    line-height: 38px;
  }
}
</style>
